package com.cloudcc.boot.utils.util;

import lombok.extern.slf4j.Slf4j;

import javax.naming.NamingException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
@Slf4j
public class DBConnection {
	static ConnectionPool cp;
	public DBConnection() {
		cp = new ConnectionPool();
		try {
			cp.createPool();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	/**
	 * 获得数据源
	 * 
	 * @return
	 * @throws NamingException
	 * @throws SQLException
	 */
	private static ThreadLocal<Connection> tl = new ThreadLocal<Connection>();

	public static Connection getConnection() throws Exception {
		Connection conn = null;
		conn = cp.getConnection();
		return conn;
	}
	
	
	/**
     * @param page 获取第几页
     * @param rows 每一页获取几条数据
     * @param conn 数据库连接
     * */
    public static ResultSet pageWithLimit(int page,int rows,Connection conn,String sql) throws SQLException {
        PreparedStatement pst=conn.prepareStatement(sql + " limit ?,?");
        pst.setInt(1,(page-1)*rows);
        pst.setInt(2,rows);
        ResultSet rs=pst.executeQuery();
        return rs;
    }
	public static void beginTransaction() throws SQLException {
		Connection conn;
		try {
			conn = getConnection();
			conn.setAutoCommit(false);
		} catch (NamingException e) {
			e.printStackTrace();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	public static void commitAndClose() {
		try {
			Connection conn = getConnection();
			if (conn != null) {
				conn.commit();
			}
			closeConn(conn);
		} catch (Exception e) {

		}
	}

	public static void rollbackAndClose() throws Exception {
		try {
			Connection conn = getConnection();
			if (conn != null) {
				conn.rollback();
			}
			closeConn(conn);
		} catch (SQLException e) {
			//
		} catch (NamingException e) {
			e.printStackTrace();
		}
	}

	private static void closeConn(Connection conn) {
		try {
			if (conn != null) {
				conn.close();
			}
			tl.remove();
		} catch (Exception e) {
		}
		conn = null;
	}
}
